package com.zy.nettypoject.netty.nio;

import io.netty.buffer.ByteBuf;
import org.junit.Test;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class TestByteBuffer {

    @Test
    public void test1() {
        try (FileChannel channel = new FileInputStream("F:\\Test\\test.txt").getChannel()) {
            ByteBuffer allocate = ByteBuffer.allocate(2);
            while (true) {
                int read = channel.read(allocate);
                if (read == -1) break;
                allocate.flip();//切换读模式
                while (allocate.hasRemaining()) {
                    byte b1 = allocate.get();
                    System.out.println((char) b1);
                }
                //切换写模式
                allocate.clear();
                //将未读的数据 指针前移
//                allocate.compact();
            }
        } catch (Exception e) {

        }
    }

    @Test
    public void test2() {
        //堆内存
        System.out.println(ByteBuffer.allocate(16).getClass());
        //堆外内存
        System.out.println(ByteBuffer.allocateDirect(16).getClass());
    }

    @Test
    public void test3() {
        ByteBuffer buffer = ByteBuffer.allocate(10);
        buffer.put(new byte[]{'1', '2', '3', '4'});
        buffer.flip();
        System.out.println((char) buffer.get());
        System.out.println((char) buffer.get());
        buffer.mark();//打个标记，准备重复读取
        System.out.println((char) buffer.get());
        System.out.println((char) buffer.get());
        buffer.reset();//从标记处重新读取
        System.out.println((char) buffer.get());
        System.out.println((char) buffer.get());

    }

    @Test
    public void test4() {
        ByteBuffer allocate = ByteBuffer.allocate(32);
        allocate.put("hello world\ntest111\nfu".getBytes());
        splitStr(allocate);
        allocate.put(("ck world" +
                "\n").getBytes());
        splitStr(allocate);
    }

    private void splitStr(ByteBuffer allocate) {
        allocate.flip();
        for (int i = 0; i < allocate.limit(); i++) {
            if ('\n' == allocate.get(i)) {
                int len = i + 1 - allocate.position();
                ByteBuffer str = ByteBuffer.allocate(len);
                for (int i1 = 0; i1 < len; i1++) {
                    str.put(allocate.get());
                }
                //开始读
                str.flip();
                while (true){
                    byte b = str.get();
                    //判断是否移动到limit位置，未读完接着读
                    if (!str.hasRemaining()){
                        break;
                    }
                    System.out.print((char) b);
                }
                System.out.println();
                str.clear();
            }
        }
        //未读完的数据，进行下一次接着读取
        allocate.compact();
    }
}
